import * as systemService from '../../services/system';

export default {
  namespace: 'admin',
  state:{
    pageAdmins:{},
  },
  reducers: {
    updatePageAdmins(state, {payload}) {
      const newstate = state;
      newstate.pageAdmins = payload;
      return newstate;
    },
    updateRow(state, {payload}) {
      const newstate = state;
      let index=null;
      const datas=newstate.pageAdmins.data;
      for(var i=0;i<datas.length;i++){
        if(datas[i].id==payload.id){
          index=i;
          break;
        }
      }
      if(index!=null){
        newstate.pageAdmins.data[index]=payload;
      }
      return newstate;
    },
    updateAdminRoles(state, {payload}) {
      const newstate = state;
      newstate.adminRoles = payload;
      return newstate;
    },
  },
  effects: {
    *getPageAdmins({payload}, {call, put}) {
      const {data} = yield call(systemService.getAdminsPage,payload);
      yield put({type: 'updatePageAdmins', payload: data});
    },
    *delete({payload}, {call, put}) {
      yield call(systemService.deleteAdmins,payload);
      yield put({type: 'getPageAdmins',payload:payload.params});
    },
    *add({payload}, {call, put}) {
      const {data} = yield call(systemService.addOrUpdateAdmin,payload);
      yield put({type: 'getPageAdmins',payload:{
        pageNumber:1,
        pageSize:10
      }});
    },
    *update({payload}, {call, put}) {
      const {data} = yield call(systemService.addOrUpdateAdmin,payload);
      yield put({type: 'updateRow',payload:data});
    },
    *getAdminRoles({payload}, {call, put}) {
      const {data} = yield call(systemService.getAdminRoles,payload);
      yield put({type: 'updateAdminRoles',payload:data});
    },
  },
  subscriptions: {

  },

}
